/*
  Exercise 8.2
  http://tronixstuff.com/tutorials - Chapter 8
  
  Use the serial monitor box to control a servo
*/

#include <Servo.h> // required library to control the servo
Servo myservo;  // create servo object to control a servo

int angle = 0;
int duration = 0;

  int getserialnumber()
  // function to get an integer from the serial monitor box, i.e. user input
  {
    int result=0;
    int q = 0;
    while (Serial.available()==0)
    {
      // do nothing until something comes into the serial buffer
    } 
    while (Serial.available()>0)
    {
      while (Serial.available()>0)
      {
        result=result*10; // move the previous digit to the next column on the left, e.g. 1 becomes 10
        // while there is data in the buffer
        q = Serial.read()-48; // read the next number in the buffer, subtract 48 to convert to the actual number
        result=result+q;
      }
      delay(5); // the processor needs a moment to process
    }
    return result;
  }

void setup()
{
  Serial.begin(9600);
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
}

void loop()
{
 // start servo at zero degrees 
  myservo.write(0);
 // get parameters from the user
  Serial.println();
  Serial.println();
  Serial.println("Enter an angle for the servo (0~180 degrees)");
  angle=getserialnumber();
  Serial.print("Enter duration in seconds to stay at ");
  Serial.print(angle);
  Serial.println(" degrees ");  
  duration=getserialnumber();
  Serial.println();
  Serial.print("Holding servo at ");
  Serial.print(angle);
  Serial.print(" degrees for ");
  Serial.print(duration);
  Serial.print(" seconds");
  // now tell the servo what to do 
  myservo.write(angle);
  delay(duration*1000);
  myservo.write(0);
}
